package com.javatiaocao.myblog.service.impl;

import com.javatiaocao.myblog.constant.CodeType;
import com.javatiaocao.myblog.mapper.UserMapper;
import com.javatiaocao.myblog.model.Role;
import com.javatiaocao.myblog.model.User;
import com.javatiaocao.myblog.service.UserService;
import com.javatiaocao.myblog.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        //查询用户各项数据
        User user = userMapper.findUserByPhone(phone);

        //没有查到数据
        if (Objects.isNull(user)){
            throw new UsernameNotFoundException(CodeType.USERNAME_NOT_EXIST.name());
        }
        //用户存在时查询角色
        List<Role> roles =userMapper.getRolesByPhone(phone);
        user.setRoles(roles);
        //记录登录时间
        TimeUtil timeUtil = new TimeUtil();
        String formatDateForSix = timeUtil.getFormatDateForSix();

        //更新用户登录时间
        userMapper.updateRecentlyLanded(user.getPhone(),formatDateForSix);

        //权限
        ArrayList<SimpleGrantedAuthority> auths = new ArrayList<>();
        for (Role role : user.getRoles()) {
            auths.add(new SimpleGrantedAuthority(role.getName()));
        }

        UserDetails userDetails = new org.springframework.security.core.userdetails.User(
                user.getPhone(),user.getPassword(),auths);
        return userDetails;
    }
}
